<?php
namespace Abo\Larasearch\V0\SyncDatabase\Adapter;
use Abo\Larasearch\V0\RedisBitMap\RbmBuilder;

/**
 * Class RedisbitmapSyncAdapter
 * Description: Redisbitmap 数据同步适配器
 * @package Abo\Larasearch\SyncDatabase\Adapter
 */
class RedisbitmapSyncAdapter
{
    /** @var $RbmBuilder RbmBuilder */
    private $RbmBuilder;

    /**
     * 同步新增逻辑
     * @param array $insertId       实体主键数组 [ 1, 2, 1008 ]
     * @param string $insertKey     分类 'color:red'
     * @return int
     */
    public function syncInsertData( array $insertId, string $insertKey )
    {
        if ( empty( $insertKey ) || empty( $insertId ) ) { return 0; }

        $insertCount = $this->RbmBuilder->initBitmap( $insertKey, $insertId );
        return $insertCount;
    }

    /**
     * 同步更新逻辑
     * @param array $updateId       实体主键数组 [ 1, 2, 1008 ]
     * @param string $updateKey     分类 'color:red'
     * @return int
     */
    public function syncUpdateData( array $updateId, string $updateKey )
    {
        if ( empty( $updateId ) || empty( $updateKey ) ) { return 0; }

        $updateCount = $this->RbmBuilder->initBitmap( $updateKey, $updateId );
        return $updateCount;
    }

    /** $deleteData => [ 1, 2, 3, 10175 ] */
    public function syncDeleteData( array $deleteKey )
    {
        if ( !$deleteKey ) {
            return true;
        }

        $i2Count = 0;
        foreach ( $deleteKey as $v2Id ) {
            if ( !$v2Id ) {
                continue;
            }
            $this->clientInstance()->docDelete( $v2Id );
            $i2Count++;
        }

        return $i2Count;
    }

    /**
     * RedisBitmap单例
     * @return RbmBuilder
     */
    public function clientInstance():RbmBuilder
    {
        if ( !$this->RbmBuilder ) {
            $this->RbmBuilder = new RbmBuilder();
        }
    }
}